(function() {
  const vendors = ['webkit', 'moz'];
  for (let idx = 0; idx < vendors.length && !window.requestAnimationFrame; ++idx) {
    const vp = vendors[idx];
    window.requestAnimationFrame = window[vp+'RequestAnimationFrame'];
    window.cancelAnimationFrame = (window[vp+'CancelAnimationFrame'] || window[vp+'CancelRequestAnimationFrame']);
  }
  if (/iP(ad|hone|od).*OS 6/.test(window.navigator.userAgent) // iOS6 is buggy
    || !window.requestAnimationFrame || !window.cancelAnimationFrame) {
    let lastTime = 0;
    window.requestAnimationFrame = function(callback) {
      const now = Date.now();
      const nextTime = Math.max(lastTime + 16, now);
      return setTimeout(function() { callback(lastTime = nextTime); }, nextTime - now);
    };
    window.cancelAnimationFrame = clearTimeout;
  }
}());

window.onload = function () {
  const clientWidth = document.documentElement.clientWidth;
  const clientHeight = document.documentElement.clientHeight;
  const oCanvas = document.getElementById('canvas');

  oCanvas.width = clientWidth;
  oCanvas.height = clientHeight;

  const originX = clientWidth / 2;
  const originY = clientHeight / 2;

  const ctx = oCanvas.getContext('2d');

  const stars = [];

  const clientRadian = Math.sqrt(clientWidth * clientWidth + clientHeight * clientHeight);

  const createStar = function () {
    let radian = Math.random() * 360 * Math.PI / 180;
    let rRadius = Math.random() * clientRadian - clientRadian / 2;
    const star = {
      x: originX + rRadius * Math.sin(radian),
      y: originY + rRadius * Math.cos(radian),
      radius: 1,
      radian: radian,
      rRadius: rRadius,
      color: '#3480BC',
      speed: Math.random() + 0.06,
      draw: function() {
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, true);
        ctx.closePath();
        ctx.fillStyle = this.color;
        ctx.fill();
      }
    };

    return star;
  }

  for (let idx = 0; idx < 800; idx++) {
    stars.push(createStar());
  }

  function draw() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    let star;

    stars.push(createStar());

    for (let idj = 0; idj < stars.length; idj++) {
      star = stars[idj];
      star.draw();

      let arr;
      if (star.rRadius > 0) {
        arr = star.rRadius + star.speed;
      } else {
        arr = star.rRadius - star.speed
      }
      star.x = originX + (arr) * Math.sin(star.radian);
      star.y = originY + (arr) * Math.cos(star.radian);
      star.rRadius = arr;

      if (star.x < 0 || star.y < 0 || star.x > oCanvas.width || star.y > oCanvas.height) {
        stars.splice(idj, 1);
      }
    }
    requestAnimationFrame(draw);
  }
  draw();
}
